﻿using KwaiXiaoDian.Entity.Common;
using KwaiXiaoDian.Entity.DO;
using KwaiXiaoDian.Entity.VO.Product;
using KwaiXiaoDian.Entity.VO.Notice;
using KwaiXiaoDian.IDao;
using KwaiXiaoDian.IService;
using Microsoft.Extensions.Logging;
using SSharing.Frameworks.NetCore.Common.Extends;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.Configuration;
using SSharing.Frameworks.NetCore.Common.Results;
using SSharing.Frameworks.NetCore.Common.Consts;
using System.Diagnostics;
using Microsoft.Extensions.Caching.Memory;

namespace KwaiXiaoDian.Service
{
    /// <summary>
    /// 商品推广数据service
    /// </summary>
    public class ProductPromoteService : BaseService<TProductPromote>, IProductPromoteService
    {
        private readonly IProductPromoteDao _productPromoteDao;
        private readonly IProductDao _productDao;
        private readonly IKwaiXiaoDianService _kwaiXiaoDianService;
        private readonly INoticeService _noticeService;
        private readonly IConfiguration _configuration;
        private readonly IMemoryCache _memoryCache;

        public ProductPromoteService(IProductPromoteDao productPromoteDao
            , IProductDao productDao
            , IKwaiXiaoDianService kwaiXiaoDianService
            , INoticeService noticeService
            , IConfiguration configuration
            , IMemoryCache memoryCache) : base(productPromoteDao)
        {
            _productPromoteDao = productPromoteDao;
            _productDao = productDao;
            _kwaiXiaoDianService = kwaiXiaoDianService;
            _noticeService = noticeService;
            _configuration = configuration;
            _memoryCache = memoryCache;
        }

        /// <summary>
        /// 获取商品推广数据
        /// </summary>
        /// <param name="productId">商品Id</param>
        /// <returns></returns>
        public GetPromoteDataResponse GetPromoteData(string productId)
        {
            GetPromoteDataResponse response = new GetPromoteDataResponse()
            {
                TotalOrderNum = 0,
                DailyOrderNum = new List<DataItem2>()
            };
            List<DataItem2> list = new List<DataItem2>();
            var now = DateTime.Now;

            //读取缓存
            var cachePromoteDataHours = _configuration["Cache.PromoteData.Hours"].ToInt(8);
            var cacheKey = string.Format("KwaiXiaoDian:Product:PromoteData:{0}", productId);
            var cacheValue = _memoryCache.Get(cacheKey);
            if (cacheValue != null)
            {
                response = (GetPromoteDataResponse)cacheValue;
                return response;
            }

            //实时获取商品推广数据
            var productInfo = _productDao.Get(p => p.ProductId == productId).FirstOrDefault();
            if (productInfo == null)
            {
                response.DailyOrderNum = list;
                return response;
            }
            var distributeItemId = productInfo.DistributeItemId;

            //总销量以商品列表页为准
            response.TotalOrderNum = productInfo.SoldCountThirtyDays ?? 0;

            var getProductDetailInfoResult = _kwaiXiaoDianService.GetProductDetailInfo(distributeItemId, millisecondsTimeout:1000);
            if (!getProductDetailInfoResult.IsSuccess)
            {
                _noticeService.SendServerChan(new SendServerChanRequest
                {
                    Text = "获取商品推广数据时发生异常!",
                    Desp = getProductDetailInfoResult.ErrorMessage
                }, isOnlyAdmin: true);

                response.DailyOrderNum = list;
                return response;
            }

            Mtp_Popularizechart_Krhu4i2eba28igfu promoteInfo = new Mtp_Popularizechart_Krhu4i2eba28igfu();//推广数据信息
            var jObj = getProductDetailInfoResult.Data.data.data;
            foreach (var item in jObj)
            {
                if (item.Key.Contains("mtp_popularize"))
                {
                    promoteInfo = item.Value.ToObject<Mtp_Popularizechart_Krhu4i2eba28igfu>();
                }
            }

            //平台下架的商品本地不删除，包括商品推广数据
            if (promoteInfo != null && promoteInfo.fields != null && promoteInfo.fields.promoteInfo != null && promoteInfo.fields.promoteInfo.itemId == 0)
            {
                response.DailyOrderNum = list;
                return response;
            }

            //推广数据总销量
            var totalOrderNum = promoteInfo.fields.promoteInfo.totalOrderNum;

            //每日销量
            var yesterday = now.Date.AddDays(-1);
            foreach (var item in promoteInfo.fields.promoteInfo.promoteList)
            {
                var dateStr = item.dateStr;
                var month = dateStr.Substring(0, 2);
                var day = dateStr.Substring(2);
                var promoteDate = string.Format("{0}-{1}-{2}", now.Year, month, day).ToDateTime();

                //更新最近一天销量，=商品列表页总销量-近30天推广数据总销量
                if (promoteDate == yesterday && item.orderNum == 0)
                {
                    item.orderNum = response.TotalOrderNum - totalOrderNum;
                }

                list.Add(new DataItem2
                {
                    Name = promoteDate.ToString(DateTimeTypeConst.CNMONTHDAY),
                    Value = item.orderNum.ToString()
                });
            }
            response.DailyOrderNum = list;

            //设置缓存
            _memoryCache.Set(cacheKey, response, DateTimeOffset.Now.AddHours(cachePromoteDataHours));

            return response;
        }
    }
}
